package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @author zhangyu
 * @data 2023/4/20 13:09
 */
@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api("菜品相关接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    private void cleanRedisDishCache(String key){
        //拿到对应的分类key来删除对应的value集合
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }

    @PostMapping
    @ApiOperation("添加菜品")
    public Result<String> addDish(@RequestBody DishDTO dishDTO) {
        dishService.addDish(dishDTO);
        String key="dish-"+dishDTO.getCategoryId();
        cleanRedisDishCache(key);
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("分页条件查询")
    public Result<PageResult> pageSelectDish(DishPageQueryDTO dishPageQueryDTO) {
        return Result.success(dishService.pageSelectDish(dishPageQueryDTO));
    }

    /**
     * 删除菜品
     */
    @DeleteMapping
    @ApiOperation("删除菜品接口")
    public Result<String> deleteDish(@RequestParam List<Long> ids) {
        dishService.deleteDish(ids);
        cleanRedisDishCache("dish-*");
        return Result.success();
    }

    /**
     * 根据菜品id回显菜品信息(DishVo)
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id回显菜品信息接口")
    public Result<DishVO> selectDishById(@PathVariable Long id) {
        return Result.success(dishService.selectDishById(id));
    }

    @PutMapping
    @ApiOperation("修改菜品")
    public Result update(@RequestBody DishDTO dishDTO) {
        log.info("修改菜品：{}", dishDTO);
        dishService.updateWithFlavor(dishDTO);
        cleanRedisDishCache("dish-*");
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> selectDishListByCategoryId(Long categoryId) {
        return Result.success(dishService.selectDishListByCategoryId(categoryId));
    }

    @PostMapping("/status/{status}")
    @ApiOperation("修改菜品状态接口")
    public Result<String> updateDishStatus(@PathVariable Integer status, Long id) {
        log.info("修改菜品状态为: {}", status == 1 ? "启售" : "下架");
        dishService.updateDishStatus(status, id);
        cleanRedisDishCache("dish-*");
        return Result.success();
    }


}
